import Vue from 'vue';
import {ActionTree, Commit, MutationTree} from 'vuex';
import {InterfaceSocket} from '@/interface/InterfaceSocket';
import * as types from '../mutation-types';

// actions 常规写法
// const actions = {
//     sendMessage(context: { commit: Commit; state: InterfaceSocket }, message: string) {
//         Vue.prototype.$socket.send(message);
//     },
// };

// mutations 常规写法
// const mutations = {
//     [types.SOCKET_ONOPEN](state: InterfaceSocket, event: any) {
//         Vue.prototype.$socket = event.currentTarget;
//         state.isConnected = true;
//     },
//     [types.SOCKET_ONCLOSE](state: InterfaceSocket, event: any) {
//         state.isConnected = false;
//     },
//     [types.SOCKET_ONERROR](state: InterfaceSocket, event: any) {
//         state.isConnected = false;
//     },
//     [types.SOCKET_ONMESSAGE](state: InterfaceSocket, message: string) {
//         state.message = message;
//     },
//     [types.SOCKET_RECONNECT](state: InterfaceSocket, count: number) {
//         state.reconnectCount = count;
//     },
//     [types.SOCKET_RECONNECT_ERROR](state: InterfaceSocket) {
//         state.reconnectError = true;
//     },
// };


export default class SocketStore {
    public static state: InterfaceSocket = {
        isConnected: false,
        message: {},
        reconnectError: false,
        reconnectCount: 0,
        messageArray: [],
    };

    public static mutations: MutationTree<InterfaceSocket> = {
        [types.SOCKET_ONOPEN](state: InterfaceSocket, event: MessageEvent) {
            Vue.prototype.$socket = event.currentTarget;
            state.isConnected = true;
        },
        [types.SOCKET_ONCLOSE](state: InterfaceSocket, event: MessageEvent) {
            state.isConnected = false;
        },
        [types.SOCKET_ONERROR](state: InterfaceSocket, event: MessageEvent) {
            state.isConnected = false;
        },
        [types.SOCKET_ONMESSAGE](state: InterfaceSocket, event: MessageEvent) {
            state.message = JSON.parse(event.data);
            state.messageArray.push(JSON.parse(event.data));
        },
        [types.SOCKET_RECONNECT](state: InterfaceSocket, count: number) {
            state.reconnectCount = count;
        },
        [types.SOCKET_RECONNECT_ERROR](state: InterfaceSocket) {
            state.reconnectError = true;
        },
    };

    public static actions: ActionTree<InterfaceSocket, any> = {
        sendMessage(context: { commit: Commit; state: InterfaceSocket }, message: string) {
            Vue.prototype.$socket.send(message);
        },
    };

}
